package net.towee.client.widgets;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Widget;

/**
 * Collection of helper methods for showing formatted data.
 * @author c58
 */
public class DataHelpers {
    private static final long ONE_KB = 1024;
    private static final long ONE_MB = ONE_KB * ONE_KB;
    private static final long ONE_GB = ONE_KB * ONE_MB;
    private static final long ONE_TB = ONE_KB * ONE_GB;
	
	/**
	 * Cut given string to size and add triple point to end of string.
	 * Return original string if it's length less then given max length.
	 * 
	 * @param str
	 * @param maxLen
	 * @return
	 */
	public static String cutString(String str, int maxLen) {
		if(str.length() > maxLen) {
			String resultString = str.substring(0, maxLen);
			
			int spPos = 0;
			if(str.charAt(maxLen) != ' ' && maxLen-(spPos=resultString.lastIndexOf(" ")) < 20){
				resultString = resultString.substring(0, spPos);
			}
			
			return resultString+"...";
		}
		else
			return str;
	}
	
	/**
	 * Format numeric Date to internationalized string.  
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {		
		return DateTimeFormat.getFormat("d MMMM yyyy").format(date);
	}
	
	/**
	 * This method return widget with formatted date/time, that automatically
	 * updated every 60 seconds. Date formated by {@link formatDateTime()} method 
	 * 
	 * @param date
	 * @return
	 */
	public static Widget formattedDateTimeWidget(final Date date) {
		final SpanPanel dateArea = new SpanPanel();
		
		// Update timer every 60 seconds
		/*Timer t = new Timer(){
			@Override
			public void run() {
				date.setTime( date.getTime()+60000 );
				dateArea.setText( formatDateTime(date) );
			}
		};
		t.schedule(60000);*/
		
		// Set initial text
		dateArea.setText( formatDateTime(date) );
		return dateArea;
	}
	
	public static String formatDateTime(Date date) {
		return DateTimeFormat.getFormat("d MMMM yyyy HH:mm").format(date);
	}

    /**
     * Returns a human-readable version of the file size (original is in * bytes).
     *
     * NOTE : Taken from Apache Commons FileUtils
     *
     * @param size The number of bytes.
     * @return A human-readable display value (includes units).
     */
    public static String humanReadableByteCount(long size) {
    	if (size / ONE_TB > 0) {
            return String.valueOf(size / ONE_TB) + " TB";
    	} else if (size / ONE_GB > 0) {
            return String.valueOf(size / ONE_GB) + " GB";
        } else if (size / ONE_MB > 0) {
                return String.valueOf(size / ONE_MB) + " MB";
        } else if (size / ONE_KB > 0) {
                return String.valueOf(size / ONE_KB) + " KB";
        } else {
                return String.valueOf(size) + " bytes";
        }
    }
}
